# encoding: utf-8

class Utility::Tencent < Utility::BasicTweet

  field :refresh_token, :type => String
  # # # # # # # # # # # # # # # #
  #
  # 从这里开始是类方法
  #
  # # # # # # # # # # # # # # # #




  # # # # # # # # # # # # # # # #
  #
  # 从这里开始是对外开放的接口
  #
  # # # # # # # # # # # # # # # #
  def search(result, options={})
    tweets = Utility.get("https://open.t.qq.com/api/search/t?&#{biuld_params(options)}", {})
    tweets = JSON.parse(tweets)
    p tweets
    if tweets['ret'].to_s == '0'
      # 成功
      result.tencent_builder tweets['data']['info']
      result.has_result      = true
      result.total_num       = tweets['data']['totalnum']
      result.is_finish       = true if ['2', '0'].include?(tweets['data']['hasnext'].to_s)
    else
      logger.info "发生错误>"
      result.error      = "#{tweets['errcode']}---#{tweets['msg']}"
      return result
    end
    result.make_success
  end

  def biuld_params(options)
    options.each do |k, v|
      options.delete(k) if v.nil? || v.to_s.empty?
    end

    options_buffer  = "&scope=all&oauth_version=2.a&access_token=#{access_token}&oauth_consumer_key=#{Oauth2::TENCENT_CLIENT_ID}&openid=#{uid}&clientip="

    options_buffer += "&keyword=#{options[:keyword]}"

    options_buffer += "&format=json&searchtype=0&needdup=1&contenttype=0&sorttype=0&msgtype=0&vip=0"

    options_buffer += "&pagesize=20&page=#{options[:page] || 1}"

    options_buffer += "&starttime=#{parse_time(options[:starttime]) || 0}"

    options_buffer += "&endtime=#{parse_time(options[:endtime].present? ? options[:endtime] : options[:searchtime]) || 0}"

    options_buffer += "&province=#{options[:province]}"

    options_buffer += "&city=#{options[:city]}"

    options_buffer += "&longitue=#{options[:longitue]}"

    options_buffer += "&latitude=#{options[:latitude]}"

    options_buffer += "&radius=#{options[:radius] || 20000}"

    options_buffer
  end

  def create_comment(commnet, mid, uid)
    result = Utility.post_j 'https://open.t.qq.com/api/t/comment', {
      :content        => commnet,
      :longitude      => '',
      :latitude       => '',
      :reid           => mid,
      :compatibleflag => 0
    }.merge(common_params)

    result["api_name"] = "create_comment"
    if error = error_rescue(result)
      return [error, result]
    else
      return [false, result]
    end
  end

  def error_rescue(result)
    return false unless result["error"]
    logger.info ">遇到错误: 请求#{result["api_name"]}时,#{result["error"]}--#{result["error"]}."
    case result["error"]
    when 10009

    when 10013

    when 21327 # token 过期
      self.status[result["api_name"]] = false
      logger.info ">处理错误: 将此账号的#{result["api_name"]}标记为过期"
      self.save
      return ERROR_RESCUE[:another_retry]
    when 20003 #被封号
      self.status[result["api_name"]] = false
      self.status["login"] = false
      logger.info ">处理错误: 此账号#{self.username}已经被腾讯封锁"
      self.save
      return ERROR_RESCUE[:another_retry]
    when 21321 # 测试未被授权
      self.status[result["api_name"]] = false
      logger.info ">处理错误: 此账号#{self.username}测试未被授权"
      self.save
      return ERROR_RESCUE[:another_retry]
    when 10022 # IP请求频次超过上限
      return ERROR_RESCUE[:im_sorry]
    when 10023 # 用户请求频次超过上限
      self.status[result["api_name"]] = false
      logger.info ">处理错误: 此账号#{self.username}请求频次超过上限"
      return ERROR_RESCUE[:another_retry]
      self.save
    when 10024 # 用户请求频次超过上限
      self.status[result["api_name"]] = false
      logger.info ">处理错误: 此账号#{self.username}请求频次超过上限"
      return ERROR_RESCUE[:another_retry]
      self.save
    else
      return ERROR_RESCUE[:im_sorry]
    end
  end

  def common_params
    {
      :oauth_consumer_key => Oauth2::TENCENT_CLIENT_ID,
      :access_token       => access_token,
      :openid             => uid,
      :clientip           => '',
      :oauth_version      => '2.a',
      :scope              => 'all',
      :format             => 'json'
    }
  end

  def auto_access
    logger.info ">重新授权: 授权即将过期,重新授权"
    result = http_client.get("https://open.t.qq.com/cgi-bin/oauth2/access_token?client_id=#{Oauth2::TENCENT_CLIENT_ID}&grant_type=refresh_token&refresh_token=#{self.refresh_token}")
    result = Rack::Utils.parse_nested_query(result.body.to_s)
    self.refresh_token = result["refresh_token"]
    self.access_token  = result["access_token"]
    self.expires_in    = Time.at Time.now + result["expires_in"].to_i
    self.save
  end


  private

  def parse_time(time)
    if time.present?
      time[10] = ' '
      Time.parse(time).to_i
    else
      nil
    end
  end

end
